from odoo import models, fields, _, api
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import logging
from odoo.exceptions import UserError

logger = logging.getLogger(__name__)


class Bad(models.Model):
    _name = 'person.bad'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    _description = 'The bad people are to be away'
    _rec_name = 'user_id'

    user_id = fields.Many2one(
        'person.info',
        string="姓名"
    )

    bad_task = fields.Many2many(
        'project.task',
        # 'name',
        string="问题任务"
    )

    problem_content = fields.Html(
        '问题表现',
    )

    deputy_director_comment = fields.Html(
        '副总监意见',
    )

    chief_director_comment = fields.Html(
        '总监意见',
    )

    teacher_comment = fields.Html(
        '老师意见',
    )

    current_user_is_group_leader = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_deputy_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_director = fields.Boolean(
        compute="_compute_current_user"
    )

    current_user_is_teacher = fields.Boolean(
        compute="_compute_current_user"
    )

    # 计算当前选中的问题人员姓名
    select_user = fields.Char(
        compute="_computer_select_user"
    )

    def _computer_select_user(self):
        self.select_user = self.user_id.name

    state = fields.Selection(
        [
            (6, '编辑'),
            (5, '副总监审批'),
            (4, '总监审批'),
            (3, '老师审批'),
            (2, '通过'),
            (1, '失败'),
        ],
        string='状态', default=6, readonly=True, copy=False, track_visibility='onchange'
    )

    comment_deputy_director_state = fields.Boolean(
        '副总监评论是否显示',
        default=False
    )

    comment_director_state = fields.Boolean(
        '总监评论是否显示',
        default=False
    )
    comment_teacher_state = fields.Boolean(
        '老师评论是否显示',
        default=False
    )

    # 判断当前用户的身份
    @api.one
    def _compute_current_user(self):
        self.current_user_is_group_leader = self.user_has_groups('sugon_system.asset_group_leader')
        self.current_user_is_deputy_director = self.user_has_groups('sugon_system.asset_deputy_director')
        self.current_user_is_director = self.user_has_groups('sugon_system.asset_director')
        self.current_user_is_teacher = self.user_has_groups('sugon_system.asset_teacher')

    @api.one
    def button_deputy_director(self):
        # 检查该人员是否在审批流中
        sql_query = """SELECT user_id, state FROM person_bad where user_id = '{id}' and state < 6 and state != 1""".format(
            id=self.user_id.id)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        if result:
            raise UserError(_('%s已经存在于问题人员审核中!') % self.user_id.name)
        else:
            # 获取全部权限组
            groups = self.env['res.groups'].sudo().search([])
            if self.current_user_is_group_leader == True:
                self.comment_deputy_director_state = True
                group = groups.search([('name', 'like', '%技术副总监%')])
                users = group.users
                for user in users:
                    Bad.call_owner(self, user)  # 向副总监组发送邮件
                return self.write({"state": 5})
            if self.current_user_is_deputy_director == True:
                self.comment_director_state = True
                group = groups.search([('name', 'like', '%技术总监%')])
                users = group.users
                for user in users:
                    print(user.name)
                    Bad.call_owner(self, user)  # 向监组发送邮件
                return self.write({"state": 4})
            if self.current_user_is_director == True:
                self.comment_teacher_state = True
                group = groups.search([('name', 'like', '%老师%')])
                users = group.users
                for user in users:
                    Bad.call_owner(self, user)  # 向老师组发送邮件
                return self.write({"state": 3})

    @api.one
    def button_chief_inspector(self):
        groups = self.env['res.groups'].sudo().search([])
        group = groups.search([('name', 'like', '%技术总监%')])
        users = group.users
        for user in users:
            Bad.call_owner(self, user)  # 向总监组发送邮件
        self.comment_director_state = True
        return self.write({"state": 4})

    @api.one
    def button_teacher(self):
        groups = self.env['res.groups'].sudo().search([])
        group = groups.search([('name', 'like', '%老师%')])
        users = group.users
        for user in users:
            Bad.call_owner(self, user)  # 向老师组发送邮件
        self.comment_teacher_state = True
        return self.write({"state": 3})

    @api.one
    def button_pass(self):
        sql_query = """update person_info set is_quit = '{state}' where name = '{name}'""".format(
            state=True, name=self.user_id.name)
        self.env.cr.execute(sql_query)
        sql_delete_user = """DELETE FROM res_users where login = '{email}'""".format(
            email=self.user_id.email)
        self.env.cr.execute(sql_delete_user)
        sql_delete_partner = """DELETE FROM res_partner where name = '{name}'""".format(
            name=self.user_id.name)
        self.env.cr.execute(sql_delete_partner)
        return self.write({"state": 2})

    @api.one
    def button_fail(self):
        return self.write({"state": 1})

    @api.one
    def call_owner(self, user):
        sender = 'zilouis@qq.com'
        passwd = 'sovlbfcttwogbhhi'
        logger.info("Here is the email addr: %s", user.email)
        receivers = user.email  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱
        mail_msg = """
            <!doctype html>
            <html>
              <head>
                <meta name="viewport" content="width=device-width">
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              </head>
              <body class="" style="background-color: #f6f6f6; font-family: sans-serif; -webkit-font-smoothing: antialiased; font-size: 14px; line-height: 1.4; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
                <table border="0" cellpadding="0" cellspacing="0" class="body" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background-color: #f6f6f6;">
                  <tr>
                    <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                    <td class="container" style="font-family: sans-serif; font-size: 14px; vertical-align: top; display: block; Margin: 0 auto; max-width: 580px; padding: 10px; width: 580px;">
                      <div class="content" style="box-sizing: border-box; display: block; Margin: 0 auto; max-width: 580px; padding: 10px;">

                        <!-- START CENTERED WHITE CONTAINER -->
                        <span class="preheader" style="color: transparent; display: none; height: 0; max-height: 0; max-width: 0; opacity: 0; overflow: hidden; mso-hide: all; visibility: hidden; width: 0;">This is preheader text. Some clients will show this text as a preview.</span>
                        <table class="main" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; background: #ffffff; border-radius: 3px;">

                          <!-- START MAIN CONTENT AREA -->
                          <tr>
                            <td class="wrapper" style="font-family: sans-serif; font-size: 14px; vertical-align: top; box-sizing: border-box; padding: 20px;">
                              <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                                <tr>
                                  <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">
                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">尊敬的{owner_name},</p>
                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">有新的问题人员申请，请尽快登录系统进行审核！</p>
                                    <table border="0" cellpadding="0" cellspacing="0" class="btn btn-primary" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%; box-sizing: border-box;">
                                      <tbody>
                                        <tr>
                                          <td align="left" style="font-family: sans-serif; font-size: 14px; vertical-align: top; padding-bottom: 15px;">
                                            <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: auto;">
                                              <tbody>
                                                <tr>
                                                  <td style="font-family: sans-serif; font-size: 14px; vertical-align: top; background-color: #3498db; border-radius: 5px; text-align: center;"> <a href="http://admin.hubusugon.cn" target="_blank" style="display: inline-block; color: #ffffff; background-color: #3498db; border: solid 1px #3498db; border-radius: 5px; box-sizing: border-box; cursor: pointer; text-decoration: none; font-size: 14px; font-weight: bold; margin: 0; padding: 12px 25px; text-transform: capitalize; border-color: #3498db;">湖北大学瑞翼工坊内部管理系统</a> </td>
                                                </tr>
                                              </tbody>
                                            </table>
                                          </td>
                                        </tr>
                                      </tbody>
                                    </table>
                                    <p style="font-family: sans-serif; font-size: 14px; font-weight: normal; margin: 0; Margin-bottom: 15px;">祝您生活愉快！</p>
                                  </td>
                                </tr>
                              </table>
                            </td>
                          </tr>

                        <!-- END MAIN CONTENT AREA -->
                        </table>

                        <!-- START FOOTER -->
                        <div class="footer" style="clear: both; Margin-top: 10px; text-align: center; width: 100%;">
                          <table border="0" cellpadding="0" cellspacing="0" style="border-collapse: separate; mso-table-lspace: 0pt; mso-table-rspace: 0pt; width: 100%;">
                            <tr>
                              <td class="content-block" style="font-family: sans-serif; vertical-align: top; padding-bottom: 10px; padding-top: 10px; font-size: 12px; color: #999999; text-align: center;">
                                <span class="apple-link" style="color: #999999; font-size: 12px; text-align: center;">版权所有©湖北大学瑞翼工坊</span>
                              </td>
                            </tr>

                          </table>
                        </div>
                        <!-- END FOOTER -->

                      <!-- END CENTERED WHITE CONTAINER -->
                      </div>
                    </td>
                    <td style="font-family: sans-serif; font-size: 14px; vertical-align: top;">&nbsp;</td>
                  </tr>
                </table>
              </body>
            </html>
        """.format(owner_name=user.name)
        message = MIMEText(mail_msg, 'html', 'utf-8')
        message['From'] = Header("湖北大学瑞翼工坊", 'utf-8')
        message['To'] = Header(user.email, 'utf-8')

        subject = '湖北大学瑞翼工坊'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP_SSL("smtp.qq.com", 465)
            smtpObj.login(sender, passwd)
            smtpObj.sendmail(sender, receivers, message.as_string())
            print("邮件发送成功")
        except Exception as e:
            raise UserError(_('邮件未发送成为!原因如下:%s') % e)
